<template>
  <div>
    <div class="input-section">
      <div class="right">
        <el-input
          v-model="searchQuery"
          placeholder="请输入活动名"
          style="
            width: 500px;
            height: 40px;
            margin-bottom: 20px;
            margin-top: 20px;
          "
          :prefix-icon="Search"
          clearable
        />
        <el-button type="primary" @click="searchActivity">搜索</el-button>

        <el-button @click="resetSearch">重置</el-button>
      </div>
      <div class="button-group">
        <el-button @click="exportToExcel" type="success">导出 Excel</el-button>
        <el-button type="primary" @click="handleAdd">新增</el-button>
      </div>
    </div>
    <el-table
      ref="tableRef"
      :data="tableData"
      style="width: 100%"
      row-key="id"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="50" />
      <el-table-column prop="id" label="社团活动id" width="80" />
      <el-table-column prop="clubName" label="所属社团" width="80" />
      <el-table-column prop="activityName" label="活动名" width="140" />
      <el-table-column prop="activityTitle" label="活动标题" width="140" />
      <el-table-column prop="activityContent" label="活动内容" width="200" />
      <el-table-column
        prop="startTime"
        label="活动开始时间"
        sortable
        width="150"
        :formatter="formatDate"
      />
      <el-table-column
        prop="endTime"
        label="活动结束时间"
        sortable
        width="150"
        :formatter="formatDate"
      />
      <el-table-column
  prop="status"
  label="状态"
  width="100"
  :filters="statusFilters"
  :filter-method="filterType"
  filter-placement="bottom-end"
>
  <template #default="{ row }">
    <el-tag :type="getStatusTagType(row.status)">
      {{ getStatusText(row.status) }}
    </el-tag>
  </template>
</el-table-column>
      <el-table-column label="操作" width="140">
        <template #default="{ row, $index }">
          <el-button size="small" @click="handleView(row)">查看</el-button>
          <el-button size="small" @click="handleEdit(row)" type="primary"
            >编辑</el-button
          >
        </template>
      </el-table-column>
    </el-table>
    <div class="pagination-section">
      <span class="record-count">共查询到 {{ total }} 条记录</span>
      <el-pagination
        background
        layout="prev, pager, next"
        :total="total"
        v-model:page-size="pageSize"
        v-model:current-page="currentPage"
        :page-sizes="[8, 16, 32, 64]"
        @current-change="handleCurrentChange"
      />
    </div>
    <!-- 查看活动详情的对话框 -->
    <el-dialog v-model="viewDialogVisible" title="活动详情" width="50%">
      <el-descriptions border :column="2">
        <el-descriptions-item label="活动ID">{{
          currentViewActivity.id
        }}</el-descriptions-item>
        <el-descriptions-item label="所属社团">{{
          currentViewActivity.clubName
        }}</el-descriptions-item>
        <el-descriptions-item label="活动名称">{{
          currentViewActivity.activityName
        }}</el-descriptions-item>
        <el-descriptions-item label="活动标题">{{
          currentViewActivity.activityTitle
        }}</el-descriptions-item>
        <el-descriptions-item label="活动内容" :span="2">
          <div style="white-space: pre-line">
            {{ currentViewActivity.activityContent }}
          </div>
        </el-descriptions-item>
        <el-descriptions-item label="开始时间">{{
          formatDate(null, null, currentViewActivity.startTime)
        }}</el-descriptions-item>
        <el-descriptions-item label="结束时间">{{
          formatDate(null, null, currentViewActivity.endTime)
        }}</el-descriptions-item>

        <el-descriptions-item label="状态">
          <el-tag :type="getStatusTagType(currentViewActivity.status)">
            {{ currentViewActivity.status }}
            <!-- 直接显示API返回的状态字符串 -->
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="活动成员" :span="2">
          <div style="display: flex; align-items: center">
            <el-button
              type="primary"
              size="small"
              @click="handleViewMembers(currentViewActivity)"
              >查看成员</el-button
            >
          </div>
        </el-descriptions-item>
      </el-descriptions>

      <template #footer>
        <el-button @click="viewDialogVisible = false">关闭</el-button>
      </template>
    </el-dialog>
    <el-dialog
      :title="isEditMode ? '编辑社团活动信息' : '新增社团活动'"
      v-model="dialogVisible"
      width="600px"
      @close="handleClose"
    >
      <el-form :model="form" label-width="100px">
        <!-- 新增模式显示社团ID -->
        <el-form-item v-if="!isEditMode" label="社团ID" prop="clubId" required>
          <el-input-number
            v-model="form.clubId"
            :min="1"
            placeholder="请输入所属社团ID"
          />
        </el-form-item>

        <!-- 编辑模式显示活动ID -->
        <el-form-item v-if="isEditMode" label="社团活动ID">
          <el-input v-model="form.id" placeholder="社团活动ID" disabled />
        </el-form-item>

        <!-- 公共字段 -->
        <el-form-item label="活动名称" prop="activityName" required>
          <el-input v-model="form.activityName" placeholder="请输入活动名称" />
        </el-form-item>

        <el-form-item label="活动标题" prop="activityTitle" required>
          <el-input v-model="form.activityTitle" placeholder="请输入活动标题" />
        </el-form-item>

        <el-form-item label="活动内容" prop="activityContent" required>
          <el-input
            type="textarea"
            v-model="form.activityContent"
            placeholder="请输入活动内容"
          />
        </el-form-item>
        <el-form-item label="活动开始时间" prop="startTime" required>
          <el-date-picker
            v-model="form.startTime"
            type="datetime"
            placeholder="请选择活动开始时间"
            value-format="YYYY-MM-DD HH:mm:ss"
          />
        </el-form-item>

        <el-form-item label="活动结束时间" prop="endTime" required>
          <el-date-picker
            v-model="form.endTime"
            type="datetime"
            placeholder="请选择活动结束时间"
            value-format="YYYY-MM-DD HH:mm:ss"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="saveEdit">保存</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script lang="ts" setup>
import { ref, computed, onMounted } from "vue";
import { ElMessage, ElMessageBox, ElLoading } from "element-plus";
import { Search } from "@element-plus/icons-vue";
import {
  getActivityAllAPI,
  deleteActivityAPI,
  addActivityAPI,
  updateActivityAPI,
} from "@/apis/activity";
import { useRouter } from "vue-router";
import * as XLSX from "xlsx";

// 导出为 Excel
const exportToExcel = () => {
  if (!tableData.value.length) {
    ElMessage.warning("没有可导出的数据");
    return;
  }
  console.log("表格数据：", tableData.value);
  // 提取你想要导出的字段
  const exportData = tableData.value.map((item) => ({
    活动ID: item.id,
    活动名称: item.activityName,
    活动标题: item.activityTitle,
    活动内容: item.activityContent,
  }));

  const worksheet = XLSX.utils.json_to_sheet(exportData);
  const workbook = XLSX.utils.book_new();
  XLSX.utils.book_append_sheet(workbook, worksheet, "社团信息");

  // 下载 Excel 文件
  XLSX.writeFile(
    workbook,
    `社团列表_${new Date().toISOString().slice(0, 10)}.xlsx`
  );
};

const router = useRouter();
interface Activity {
  id: number;
  clubId: number;
  activityName: string | null;
  activityTitle: string;
  activityContent: string;
  startTime: string;
  endTime: string;
  status: string;
  clubVO: {
    clubName: string;
  };
  clubName?: string;
}

const filterType = (value: string, row: Activity) => {
  // 统一处理状态值为字符串进行比较
  return String(row.status) === String(value);
};
const statusFilters = [
  { text: "待审核", value: "0" },
  { text: "确定举办", value: "1" },
  { text: "进行中", value: "2" },
  { text: "已结束", value: "3" },
  { text: "已取消", value: "4" }
];
const tableRef = ref<any>();
const searchQuery = ref("");
const dialogVisible = ref(false);
const form = ref<Activity>({
  id: 0,
  clubId: 0,
  activityName: "",
  activityTitle: "",
  activityContent: "",
  startTime: "",
  endTime: "",
  status: "",
  clubVO: {
    clubName: "",
  },
  clubName: "",
});
const currentPage = ref(1);
const pageSize = ref(8); // 设置为8条/页
const total = ref(0);
const tableData = ref([]);

// 页码变化处理函数
const handleCurrentChange = (newPage: number) => {
  currentPage.value = newPage;
  loadTableData();
};

const loadTableData = async () => {
  try {
    // 打印请求参数，方便调试
    console.log("请求参数:", {
      currentPage: currentPage.value,
      pageSize: pageSize.value,
    });

    const response = await getActivityAllAPI(
      currentPage.value,
      pageSize.value,
      null
    );
    console.log("API Response:", response);

    if (response.code === 0 && response.data) {
      // 处理可能出现的系统错误（50000）
      if (response.code === 50000) {
        throw new Error(response.message || "系统错误");
      }

      tableData.value = response.data.records || [];
      total.value = response.data.total || 0;

      // 如果请求有数据但返回空数组（说明页码超出了范围）
      if (tableData.value.length === 0 && currentPage.value > 1) {
        currentPage.value = 1;
        loadTableData();
      }
    } else {
      throw new Error(response.message || "加载数据失败");
    }
  } catch (error) {
    console.error("加载数据时发生错误:", error);
    ElMessage.error("加载数据失败: " + error.message);
    tableData.value = [];
    total.value = 0;
  }
};

const handleViewMembers = (activity: Activity) => {
  router.push({
    name: "activityMember", // 使用路由名称，必须与路由配置中的name一致
    params: { id: activity.id }, // 传递params参数
    query: {
      name: activity.activityName, // 传递query参数
    },
  });
};

// 查看对话框相关状态
const viewDialogVisible = ref(false);
const currentViewActivity = ref<Activity>({
  id: 0,
  clubId: 0,
  activityName: "",
  activityTitle: "",
  activityContent: "",
  startTime: "",
  endTime: "",
  status: "",
  clubVO: {
    clubName: "",
  },
  clubName: "",
});

// 修改handleView方法
const handleView = (row: Activity) => {
  currentViewActivity.value = { ...row };
  viewDialogVisible.value = true;
};

// 添加状态显示方法
const getStatusText = (status: number | string) => {
  // 统一转为字符串处理
  const statusStr = String(status).trim();
  
  const statusMap: Record<string, string> = {
    '0': '待审核',
    '1': '确定举办',
    '2': '进行中',
    '3': '已结束',
    '4': '已取消',
    '待审核': '待审核',
    '确定举办': '确定举办',
    '进行中': '进行中',
    '已结束': '已结束',
    '已取消': '已取消'
  };
  
  return statusMap[statusStr] || '未知状态';
};

// 修改getStatusTagType函数
const getStatusTagType = (status: number | string) => {
  const statusStr = String(status).trim();
  const typeMap: Record<string, string> = {
    '0': 'info',
    '1': 'success',
    '2': 'warning',
    '3': '',
    '4': 'danger',
    '待审核': 'info',
    '确定举办': 'success',
    '进行中': 'warning',
    '已结束': '',
    '已取消': 'danger'
  };
  return typeMap[statusStr] || 'info';
};
const handleDelete = async (index: number) => {
  try {
    const activity = tableData.value[index];
    if (!activity?.id) {
      ElMessage.warning("未找到要删除的活动");
      return;
    }

    await ElMessageBox.confirm("确定要删除此活动吗？", "提示", {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning",
    });

    const loading = ElLoading.service({
      lock: true,
      text: "删除中...",
      background: "rgba(0, 0, 0, 0.7)",
    });

    const response = await deleteActivityAPI(activity.id);
    loading.close();

    if (response.code === 0) {
      ElMessage.success("删除成功");
      await loadTableData(); // 等待数据刷新完成
    } else {
      throw new Error(response.message || "删除失败");
    }
  } catch (error) {
    if (error !== "cancel") {
      console.error("删除失败:", error);
      ElMessage.error(error.message || "删除失败");
      await loadTableData();
    }
  }
};
const handleBatchDelete = async () => {
  try {
    if (selectedRows.value.length === 0) {
      return ElMessage.warning("请至少选择一条记录");
    }

    await ElMessageBox.confirm(
      `确定要删除选中的 ${selectedRows.value.length} 个活动吗？`,
      "提示",
      {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
        distinguishCancelAndClose: true,
      }
    );

    const loading = ElLoading.service({
      lock: true,
      text: `正在删除 ${selectedRows.value.length} 个活动...`,
      background: "rgba(0, 0, 0, 0.7)",
    });

    const ids = selectedRows.value.map((item) => item.id);
    const response = await deleteActivityAPI(ids);
    loading.close();

    if (response.code === 0) {
      ElMessage.success(`成功删除 ${ids.length} 个活动`);
      selectedRows.value = [];
      await loadTableData();
    } else {
      throw new Error(response.message || "批量删除失败");
    }
  } catch (error) {
    if (error !== "cancel") {
      console.error("批量删除失败:", error);
      ElMessage.error(error.message || "批量删除失败");
      await loadTableData();
    }
  }
};

const isEditMode = ref(false);

const handleAdd = () => {
  isEditMode.value = false;
  form.value = {
    id: 0,
    clubId: 0, // 新增时需要填写的社团ID
    activityName: "",
    activityTitle: "",
    activityContent: "",
    startTime: "",
    endTime: "",
    createTime: "",
    updateTime: "",
    status: 0,
    isDelete: 0,
    clubName: "",
  };
  dialogVisible.value = true;
};

const handleEdit = (row: Activity) => {
  isEditMode.value = true;
  form.value = {
    ...row,
    // 确保时间格式正确
    startTime: row.startTime || "",
    endTime: row.endTime || "",
  };
  dialogVisible.value = true;
};

const saveEdit = async () => {
  try {
    const {
      id,
      clubId,
      activityName,
      activityTitle,
      activityContent,
      startTime,
      endTime,
    } = form.value;

    // 验证逻辑
    if (
      !activityName ||
      !activityTitle ||
      !activityContent ||
      !startTime ||
      !endTime
    ) {
      ElMessage.warning("请填写完整的活动信息");
      return;
    }

    // 新增时需要验证clubId
    if (!isEditMode.value && (!clubId || clubId <= 0)) {
      ElMessage.warning("请输入有效的社团ID");
      return;
    }

    let response;
    if (!isEditMode.value) {
      // 新增逻辑
      response = await addActivityAPI({
        clubId,
        activityName,
        activityTitle,
        activityContent,
        startTime,
        endTime,
      });
    } else {
      // 编辑逻辑
      response = await updateActivityAPI({
        id,
        activityName,
        activityTitle,
        activityContent,
        startTime,
        endTime,
      });
    }

    if (response.code === 0) {
      ElMessage.success(isEditMode.value ? "活动更新成功" : "活动创建成功");
      dialogVisible.value = false;
      await loadTableData();
    } else {
      throw new Error(response.message || "操作失败");
    }
  } catch (error) {
    console.error("操作失败:", error);
    ElMessage.error(error.message || "操作失败，请稍后重试");
  }
};

const handleClose = () => {
  dialogVisible.value = false;
  form.value = {
    id: 0,
    activityName: "",
    activityTitle: "",
    activityContent: "",
    startTime: "",
    endTime: "",
  };
};
const searchActivity = async () => {
  if (!searchQuery.value) {
    ElMessage.warning("请输入社团ID");
    return;
  }

  try {
    const response = await getActivityAllAPI(
      1, // 搜索时重置到第一页
      pageSize.value,
      String(searchQuery.value) // 传入具体的ID值
    );

    if (response.code === 0) {
      tableData.value = response.data?.records || [];
      total.value = response.data?.total || 0;

      if (tableData.value.length === 0) {
        ElMessage.warning("未找到匹配的社团");
      }
    }
  } catch (error) {
    ElMessage.error("搜索失败");
    console.error("Search error:", error);
  }
};

// 重置搜索
const resetSearch = () => {
  searchQuery.value = "";
  currentPage.value = 1;
  loadTableData(); // 调用获取全部的方法
};
// 选中行变化事件
const handleSelectionChange = (rows: any[]) => {
  selectedRows.value = rows;
};

onMounted(() => {
  loadTableData();
});
const currentEditId = ref<number | null>(null);
const formatDate = (row, column, cellValue) => {
  if (!cellValue) return "";
  const date = new Date(cellValue);
  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, "0");
  const day = String(date.getDate()).padStart(2, "0");
  const hours = String(date.getHours()).padStart(2, "0");
  const minutes = String(date.getMinutes()).padStart(2, "0");
  const seconds = String(date.getSeconds()).padStart(2, "0");
  return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
};

const selectedRows = ref<Activity[]>([]);
</script>

<style scoped>
.input-section {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
.right {
  display: flex;
  align-items: center;
  gap: 10px;
}
.button-group {
  display: flex;
  gap: 10px;
}

.pagination-section {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-top: 10px;
}

.record-count {
  font-size: 14px;
  color: #666;
}

.el-table {
  margin-bottom: 20px;
}

.el-pagination {
  justify-content: center;
}
</style>
